import tkinter as tk
import pyttsx3
import time
import threading
import json
import random
from collections import deque

class WordWindow:
    def __init__(self, word, phonetic, meaning, engine, master=None):
        self.window = tk.Toplevel()
        self.window.overrideredirect(True)  # 移除标题栏和边框
        
        # 随机背景颜色
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)
        bg_color = f"#{r:02x}{g:02x}{b:02x}"
        self.window.configure(bg=bg_color)
        
        # 确定文字颜色
        text_color = '#000000' if (r*0.299 + g*0.587 + b*0.114) > 186 else '#ffffff'
        
        # 限制在主窗口内
        if master is None:
            master = self.window.master
        master.update_idletasks()  # 确保窗口尺寸已更新
        master_width = master.winfo_width()
        master_height = master.winfo_height()
        x = random.randint(0, master_width - 300)
        y = random.randint(50, master_height - 250)  # 确保在白色区域内
        self.window.geometry(f"300x200+{x}+{y}")
        
        # 显示单词、音标和含义
        self.word_label = tk.Label(self.window, text=word, font=('Arial', 24), bg=bg_color, fg=text_color)
        self.word_label.pack(pady=5)

        self.phonetic_label = tk.Label(self.window, text=phonetic, font=('Arial', 18), bg=bg_color, fg=text_color)
        self.phonetic_label.pack(pady=5)
        
        self.meaning_label = tk.Label(self.window, text=meaning, font=('Arial', 18), bg=bg_color, fg=text_color)
        self.meaning_label.pack(pady=5)
        
        # 朗读单词
        threading.Thread(target=lambda: engine.say(word) or engine.runAndWait()).start()

class WordMemorizer:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("单词速记")
        self.root.state('zoomed')  # 初始最大化
        self.root.configure(bg='#f5f5dc')  # 米白色背景
        self.root.protocol("WM_DELETE_WINDOW", self.on_close)  # 关闭窗口时调用
        
        # 初始化语音引擎
        self.engine = pyttsx3.init()
        self.engine.setProperty('rate', 150)
        
        # 加载单词数据
        self.words = self.load_words()
        self.current_word_index = 0
        self.repeat_count = 0
        self.max_repeats = 20
        
        # 窗口队列
        self.window_queue = deque(maxlen=5)
        
        # 创建界面元素
        self.setup_ui()
        
        # 标志位
        self.is_running = False
    
    def load_words(self):
        try:
            with open('words.json', 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            return [
                {"word": "hello", "phonetic": "/həˈloʊ/", "meaning": "你好"},
                {"word": "world", "phonetic": "/wɜːrld/", "meaning": "世界"},
                {"word": "computer", "phonetic": "/kəmˈpjuːtər/", "meaning": "计算机"}
            ]
    
    def setup_ui(self):
        # 顶部显示当前单词和进度
        self.progress_frame = tk.Frame(self.root, bg='#4f4f4f')  # 深灰色背景
        self.progress_frame.pack(fill=tk.X, padx=5, pady=5)
        
        self.current_word_label = tk.Label(self.progress_frame, text="当前单词: ", font=('Arial', 16), bg='#4f4f4f', fg='#ffffff')
        self.current_word_label.pack(side=tk.LEFT)
        
        self.word_display_label = tk.Label(self.progress_frame, text="", font=('Arial', 16), bg='#4f4f4f', fg='#ffffff')
        self.word_display_label.pack(side=tk.LEFT)
        
        self.progress_label = tk.Label(self.progress_frame, text="进度: 0/0", font=('Arial', 16), bg='#4f4f4f', fg='#ffffff')
        self.progress_label.pack(side=tk.RIGHT)
        
        # 控制按钮
        self.control_frame = tk.Frame(self.root, bg='#f5f5dc')  # 米白色背景
        self.control_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        self.start_button = tk.Button(self.control_frame, text="开始", command=self.start_memorizing)
        self.start_button.pack(side=tk.LEFT, padx=5)

    def create_word_window(self):
        if self.current_word_index >= len(self.words):
            self.is_running = False
            return
        
        current_word = self.words[self.current_word_index]
        
        # 更新主窗口显示
        self.current_word_label.config(text=f"当前单词: {current_word['word']}")
        self.word_display_label.config(text=f"{current_word['phonetic']}  {current_word['meaning']}")
        self.progress_label.config(text=f"进度: {self.current_word_index + 1}/{len(self.words)} (重复: {self.repeat_count + 1}/{self.max_repeats})")
        
        # 创建新的弹出窗口
        window = WordWindow(current_word["word"], current_word["phonetic"], current_word["meaning"], self.engine, master=self.root)
        
        # 管理窗口队列
        if len(self.window_queue) >= 5:
            old_window = self.window_queue.popleft()
            old_window.window.destroy()
        
        self.window_queue.append(window)
        
        self.repeat_count += 1
        if self.repeat_count >= self.max_repeats:
            self.repeat_count = 0
            time.sleep(2)  # 延迟2秒
            while self.window_queue:
                window = self.window_queue.popleft()
                window.window.destroy()
            self.current_word_index += 1
    
    def start_memorizing(self):
        self.start_button.pack_forget()  # 点击后隐藏按钮
        self.is_running = True
        threading.Thread(target=self.memorize_loop, daemon=True).start()
    
    def stop_memorizing(self):
        self.is_running = False
        # 清除所有弹出窗口
        while self.window_queue:
            window = self.window_queue.popleft()
            window.window.destroy()
    
    def memorize_loop(self):
        while self.is_running:
            self.root.after(0, self.create_word_window)
            time.sleep(2)  # 每2秒创建一个新窗口
    
    def on_close(self):
        self.stop_memorizing()
        self.root.destroy()
    
    def run(self):
        self.root.mainloop()

if __name__ == "__main__":
    app = WordMemorizer()
    app.run()
